Page({
  data: {
    mode: 0, // 0: 自取, 1: 外卖
    recommendList: [
      { img: '/pages/images/coffee001.jpg', name: '气泡美式', price: 26 },
      { img: '/pages/images/coffee002.jpg', name: '美式咖啡', price: 10 },
      { img: '/pages/images/coffee003.jpeg', name: '卡布奇诺', price: 20 },
      { img: '/pages/images/exhibit01.jpeg', name: '日月星辰', price: 32 },
      { img: '/pages/images/exhibit02.jpeg', name: '雪落海滨', price: 35 }
    ],
    cateList: [
      '挂耳礼盒', '不含咖啡', '虹吸/手冲', '风味咖啡', '意式经典'
    ],
    currentCate: 0,
    goodsListAll: [{
      cate_name: '挂耳礼盒',
      goods: [{
        id: 1,
        name: '气泡美式',
        desc: '清爽气泡与浓缩咖啡的碰撞',
        price: '26',
        img: '/pages/images/coffee001.jpg'
      }, {
        id: 2,
        name: '美式咖啡',
        desc: '经典浓郁，唤醒活力',
        price: '10',
        img: '/pages/images/coffee002.jpg'
      }, {
        id: 3,
        name: '卡布奇诺',
        desc: '绵密奶泡与意式浓缩的完美融合',
        price: '20',
        img: '/pages/images/coffee003.jpeg'
      }, {
        id: 4,
        name: '日月星辰',
        desc: '特调风味，口感独特',
        price: '32',
        img: '/pages/images/exhibit01.jpeg'
      }, {
        id: 5,
        name: '雪落海滨',
        desc: '清新的海洋风味拿铁',
        price: '35',
        img: '/pages/images/exhibit02.jpeg'
      }, {
        id: 6,
        name: '牧羊少年',
        desc: '带有坚果风味的醇厚咖啡',
        price: '35',
        img: '/pages/images/exhibit03.jpeg'
      }]
    }, {
      cate_name: '不含咖啡',
      goods: []
    }, {
      cate_name: '虹吸/手冲',
      goods: []
    }, {
      cate_name: '风味咖啡',
      goods: []
    }, {
      cate_name: '意式经典',
      goods: []
    }],
    goodsList: [],
    showStoreInfoDialog: false,
    showGoodsDialog: false,
    selectedGoods: {},
    selectedOptions: {},
    quantity: 1,
    tempOptions: ['正常冰', '少冰', '温', '热'],
    selectedTemp: 0,
    sweetnessOptions: ['七分糖', '五分糖', '三分糖', '无糖', '全糖'],
    selectedSweetness: 0,
    totalPrice: '0.00',
    showCartDialog: false,
    cartList: [],
    cartTotalNum: 0,
    cartTotalPrice: 0,
    cartTotalPriceString: "0.00",
    goodsQuantities: {},
    goodsRemark: ''
  },
  onLoad(options) {
    if (options && options.mode !== undefined) {
      this.setData({ mode: Number(options.mode) });
    }
    this.updateGoodsList(Number(options && options.mode !== undefined ? options.mode : 0));
  },
  onShow() {
    // 新增：检测是否需要清空购物车
    if (wx.getStorageSync('cartCleared')) {
      this.clearCart();
      wx.removeStorageSync('cartCleared');
    }
    // 兼容首页tabBar跳转传参
    const pages = getCurrentPages();
    if (pages.length > 1 && pages[pages.length-2].route === 'pages/index/index') {
      const indexPage = pages[pages.length-2];
      if (typeof indexPage.getPendingCateMode === 'function') {
        const pendingMode = indexPage.getPendingCateMode();
        if (pendingMode === 1) {
          this.setData({ mode: 1 });
          this.updateGoodsList(1);
          indexPage.clearPendingCateMode();
        } else if (pendingMode === 0) {
          this.setData({ mode: 0 });
          this.updateGoodsList(0);
          indexPage.clearPendingCateMode();
        }
      }
    }
  },
  switchMode(e) {
    const mode = Number(e.currentTarget.dataset.mode);
    this.setData({ mode });
    this.updateGoodsList(mode);
  },
  updateGoodsList(mode) {
    // mode: 0 自取，1 外卖
    let goodsList = JSON.parse(JSON.stringify(this.data.goodsListAll));
    if (mode === 1) {
      // 外卖模式，移除日月星辰
      goodsList[0].goods = goodsList[0].goods.filter(g => g.name !== '日月星辰');
    }
    this.setData({ goodsList });
  },
  switchCate(e) {
    this.setData({ currentCate: Number(e.currentTarget.dataset.idx) });
  },
  showStoreInfo() {
    this.setData({ showStoreInfoDialog: true });
  },
  hideStoreInfo() {
    this.setData({ showStoreInfoDialog: false });
  },
  callStore() {
    wx.makePhoneCall({ phoneNumber: '16666666666' });
  },
  addToCart(e) {
    this.showGoodsDialog(e);
  },
  showGoodsDialog(e) {
    const item = e.currentTarget.dataset.item;
    if (!item) return;
    this.setData({
      selectedGoods: item,
      showGoodsDialog: true,
      quantity: 1,
      selectedTemp: 0,
      selectedSweetness: 0,
      goodsRemark: ''
    });
    this._recalculatePrice();
  },
  hideGoodsDialog() {
    this.setData({ showGoodsDialog: false, selectedGoods: null });
  },
  selectTemp(e) {
    this.setData({
      selectedTemp: e.currentTarget.dataset.idx
    });
    this._recalculatePrice();
  },
  selectSweetness(e) {
    this.setData({
      selectedSweetness: e.currentTarget.dataset.idx
    });
    this._recalculatePrice();
  },
  decreaseQuantity() {
    if (this.data.quantity > 1) {
      this.setData({
        quantity: this.data.quantity - 1
      });
      this._recalculatePrice();
    }
  },
  increaseQuantity() {
    const newQuantity = this.data.quantity + 1;
    const price = this.data.selectedGoods.price || 0;
    this.setData({ 
      quantity: newQuantity,
      totalPrice: (price * newQuantity).toFixed(2)
    });
    this._recalculatePrice();
  },
  addToCartFinal() {
    const { selectedGoods, quantity, tempOptions, selectedTemp, sweetnessOptions, selectedSweetness, goodsRemark } = this.data;
    const specId = `${tempOptions[selectedTemp]}_${sweetnessOptions[selectedSweetness]}`;
    const uniqueId = `${selectedGoods.id}_${specId}_${goodsRemark || ''}`;
    let cartList = this.data.cartList;
    const itemIndex = cartList.findIndex(item => item.uniqueId === uniqueId);
    if (itemIndex > -1) {
      cartList[itemIndex].quantity += quantity;
      cartList[itemIndex].remark = goodsRemark;
    } else {
      cartList.push({
        ...selectedGoods,
        uniqueId: uniqueId,
        quantity: quantity,
        specText: `${tempOptions[selectedTemp]} / ${sweetnessOptions[selectedSweetness]}`,
        price: parseFloat(selectedGoods.price),
        remark: goodsRemark
      });
    }
    this.setData({
      cartList: cartList,
      showGoodsDialog: false,
    });
    this.updateCart();
  },
  _updateCartInfo() {
    const cart = this.data.cart || [];
    const totalQuantity = cart.reduce((sum, item) => sum + item.quantity, 0);
    const cartTotalPrice = cart.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2);
    this.setData({ totalQuantity, cartTotalPrice });
  },
  _recalculatePrice() {
    const price = parseFloat(this.data.selectedGoods.price);
    this.setData({
      totalPrice: (price * this.data.quantity).toFixed(2)
    });
  },
  showCartDialog() {
    if (this.data.cartList.length > 0) {
      this.setData({
        showCartDialog: true
      });
    }
  },
  hideCartDialog() {
    this.setData({
      showCartDialog: false
    });
  },
  clearCart() {
    this.setData({
      cartList: [],
      showCartDialog: false,
    });
    wx.removeStorageSync('cartList');
    wx.removeStorageSync('cartTotalPriceString');
    this.updateCart();
  },
  increaseCartItemQuantity(e) {
    const uniqueId = e.currentTarget.dataset.uniqueid;
    const cartList = this.data.cartList;
    const itemIndex = cartList.findIndex(item => item.uniqueId === uniqueId);
    if (itemIndex > -1) {
      cartList[itemIndex].quantity += 1;
      this.setData({
        cartList: cartList
      });
      this.updateCart();
    }
  },
  decreaseCartItemQuantity(e) {
    const uniqueId = e.currentTarget.dataset.uniqueid;
    const cartList = this.data.cartList;
    const itemIndex = cartList.findIndex(item => item.uniqueId === uniqueId);
    if (itemIndex > -1) {
      if (cartList[itemIndex].quantity > 1) {
        cartList[itemIndex].quantity -= 1;
      } else {
        cartList.splice(itemIndex, 1);
      }
      this.setData({
        cartList: cartList
      });
      this.updateCart();

      if (cartList.length === 0) {
        this.hideCartDialog();
      }
    }
  },
  navigateToCheckout: function() {
    wx.setStorageSync('cartList', this.data.cartList);
    wx.setStorageSync('cartTotalPriceString', this.data.cartTotalPriceString);
    wx.navigateTo({
      url: '/pages/checkout/index'
    });
  },
  doNothing: function (e) {
    // 阻止事件冒泡
  },
  updateCart() {
    let cartList = this.data.cartList;
    let totalNum = 0;
    let totalPrice = 0;
    let goodsQuantities = {};

    cartList.forEach(item => {
      totalNum += item.quantity;
      totalPrice += (parseFloat(item.price) || 0) * item.quantity;
      item.subtotal = ((parseFloat(item.price) || 0) * item.quantity).toFixed(2);
      
      if (item.id) {
          goodsQuantities[item.id] = (goodsQuantities[item.id] || 0) + item.quantity;
      }
    });

    this.setData({
      cartList: cartList,
      cartTotalNum: totalNum,
      cartTotalPrice: totalPrice,
      cartTotalPriceString: totalPrice.toFixed(2),
      goodsQuantities: goodsQuantities
    })
  },
  confirmAddToCart: function () {
    this.addToCartFinal();
  },
  decreaseGoodsQuantity: function(e) {
    const goods = e.currentTarget.dataset.item;
    const goodsId = goods.id;
    let cartList = this.data.cartList;

    for (let i = cartList.length - 1; i >= 0; i--) {
        if (cartList[i].id === goodsId) {
            cartList[i].quantity--;
            if (cartList[i].quantity === 0) {
                cartList.splice(i, 1);
            }
            break;
        }
    }
    
    this.setData({
        cartList: cartList
    });
    
    this.updateCart();
  },
  onGoodsRemarkInput(e) {
    this.setData({ goodsRemark: e.detail.value });
  }
}); 